package com.ld.hpfs.web.controller;


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.MainService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class MainController {
	private static final Logger logger = LoggerFactory.getLogger(MainController.class);

	@Autowired
	private MainService mainService;
	
		
	@RequestMapping(value = "/getMainList")
	public void getUserRightsList(ExtPager page,HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		HashMap<String,Object> param = new HashMap<String,Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<Map<String,String>> field = page.getSortField();
			StringBuffer sort = new StringBuffer("");
		 	User user = (User)session.getAttribute(WebConstants.CURRENT_USER);				
			  if(user !=null){
				param.put("pageEnd",page.getStart() + page.getLimit());
				if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
			        	sort.append(map.get("property") + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} else  {
					param.put("orderBy", " GROUP_HID");
				}				
				param.put("pageStart", page.getStart());	
				String language = (String) session
						.getAttribute(WebConstants.CURRENT_LANG);
				param.put("language", language);
			ArrayList<HashMap<String,Object>> logs = mainService.getMainList(param);
			if(logs!=null&&logs.size()>0){
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", logs);
			} else {
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", "");
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		 }else{
	 		writer.print("");
		  }
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	
	@RequestMapping(value = "/editMain",method = RequestMethod.POST)
	public void editMain(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String groupName = (String)request.getParameter("groupName") == null ? null : (String)request.getParameter("groupName");
		String groupDesc = (String)request.getParameter("groupDesc") == null ? null : (String)request.getParameter("groupDesc");
		String groupId = (String)request.getParameter("groupId") == null ? null : (String)request.getParameter("groupId");
		HashMap<String,Object> result = new HashMap<String,Object>();
		 HashMap<String,Object> param = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try{
			String company_id = (String)session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			String companyId = mainService.getCompanyId(groupId);
			if(company_id.equals(companyId)){//判断当前登录公司与创建此数据套的公司是否一致
					    param = new HashMap<String,Object>();				
					    param.put("creator_id", user.getUserId());
						param.put("group_name", groupName);
					 	param.put("group_desc", groupDesc);					 	
					 	param.put("creator_company_id", company_id);
						int ret;						
						param.put("group_id", groupId);														
						ret = mainService.updateMain(param); 							 														 						
						if(ret == 0){
							result.put("resultcode",0);
						} else {
							result.put("resultcode",9);
						}				
				}else{
					result.put("resultcode", 2);
				}
			writer.print(JackJson.fromObjectToJson(result));
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	@RequestMapping(value = "/addMain", method = RequestMethod.POST )
	public void addMain(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String groupName = (String)request.getParameter("groupName") == null ? null : (String)request.getParameter("groupName");
		String groupDesc = (String)request.getParameter("groupDesc") == null ? null : (String)request.getParameter("groupDesc");		
		HashMap<String,Object> result = new HashMap<String,Object>();
		 HashMap<String,Object> param = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try{
			String company_id = (String)session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);			
					    param = new HashMap<String,Object>();				
					    param.put("creator_id", user.getUserId());
						param.put("group_name", groupName);
					 	param.put("group_desc", groupDesc);					 	
					 	param.put("creator_company_id", company_id);
					 	param.put("create_time", Tools.getCurrentDay());
						int ret;
						HashMap<String,Object> check = mainService.checkGroupName(groupName);
						if(check==null){
						ret = mainService.insertMain(param); }else{ret = 1;}							 														 						
						if(ret == 0){
							result.put("resultcode",0);
						} else if(ret == 1){
							result.put("resultcode",1);
						}
						else {
							result.put("resultcode",9);
						}				
				
			writer.print(JackJson.fromObjectToJson(result));
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	@RequestMapping(value = "/copyMain",method = RequestMethod.POST)
	public void copyMain(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String groupName = (String)request.getParameter("groupName") == null ? null : (String)request.getParameter("groupName");
		String groupDesc = (String)request.getParameter("groupDesc") == null ? null : (String)request.getParameter("groupDesc");
		String groupId = (String)request.getParameter("groupId") == null ? null : (String)request.getParameter("groupId");
		HashMap<String,Object> result = new HashMap<String,Object>();
		 HashMap<String,Object> param = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try{
			String company_id = (String)session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user!=null){
					    param = new HashMap<String,Object>();
					
					    param.put("creator_id", user.getUserId());
						param.put("group_name", groupName);
					 	param.put("group_desc", groupDesc);
					 	param.put("src_group_id",groupId);
					 	param.put("creator_company_id", company_id);
					 	param.put("create_time", Tools.getCurrentDay());
						int ret;						
						 HashMap<String,Object> check = mainService.checkGroupName(groupName);
						 if(check == null ){
							ret = mainService.copyMain(param); }
						 else{ret = 1;}
						
						if(ret == 0){
							result.put("resultcode",0);
						}else if(ret == 1){
							result.put("resultcode", 1);
							}
						 else {
							result.put("resultcode",9);
						}
				
				}else{
					result.put("resultcode", 9);
				}
			writer.print(JackJson.fromObjectToJson(result));
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	@RequestMapping(value = "/deleteMain",method = RequestMethod.POST)
	public void deleteMain(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String groupId = (String)request.getParameter("groupId") == null ? null : (String)request.getParameter("groupId");
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");		
		try {	
			String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		//	User user = (User)session.getAttribute(WebConstants.CURRENT_USER);			
			String companyId = mainService.getCompanyId(groupId);
			HashMap<String,Object> check = mainService.checkGroupId(groupId);
			if(company_id.equals(companyId)){
				if(check == null){
				HashMap<String, Object> param = new HashMap<String, Object>();				
				param.put("group_id", groupId);
				int ret = mainService.deleteMain(param);
				if(ret == 0){
					result.put("resultcode",0);
				}else{
					result.put("resultcode",9);
				 }
				}else{result.put("resultcode",3);}
			}else{result.put("resultcode",2);}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	 }
	
	@RequestMapping(value = "/setQuoteMain",method = RequestMethod.POST)
	public void setQuoteMain(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String groupId = (String)request.getParameter("groupId") == null ? null : (String)request.getParameter("groupId");
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");		
		try {	
			String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user != null){
				HashMap<String, Object> param = new HashMap<String, Object>();				
				param.put("group_id", groupId);
				param.put("company_id", company_id);
				int ret = mainService.setQuoteMain(param);
				if(ret == 0){
					result.put("resultcode",0);
				}else{
					result.put("resultcode",9);
				}
			}else{
		 		writer.print("");
			  }
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	 }
	
	/**
	 * 修改主数据套时判断当前公司是否已有数据，若有则不能删除
	 */
	@RequestMapping(value = "/checkVoucherFromCompany")
	public void checkVoucherFromCompany(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){		
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");		
		try {	
			String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user != null){
				HashMap<String, Object> param = new HashMap<String, Object>();				
				param.put("company_id", company_id);
				int ret = mainService.checkVoucherFromCompany(param);
				if(ret == 0){
					result.put("resultcode",0);
				}else{
					result.put("resultcode",9);
				}
			}else{
		 		writer.print("");
			  }
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	 }
}